package com.mygame.components

import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.entity.state.StateComponent
import com.mygame.Const
import kotlin.jvm.optionals.getOrNull

class HuntTagComponent : Component() {
    private val speed = 100.0 // 移动速度，单位：像素/秒
    private var tagEntity: Entity? = null
    private var minDistance = 50
    private lateinit var stateComponent: StateComponent
    override fun onAdded() {
        stateComponent = entity.getComponent(StateComponent::class.java)
        tagEntity = entity.properties.getValueOptional<Entity>(Const.TAG_ENTITY).getOrNull()
    }

    fun setIdleDistance(distance: Int) {
        minDistance = distance
    }

    override fun onUpdate(tpf: Double) {
        tagEntity?.let {
            if (stateComponent.currentState == ATTACK){
                return
            }
            //计算两点之间的距离
            val distance = it.center.distance(entity.center)
            //println("distance=$distance")
            if (distance > minDistance) {
                stateComponent.changeState(RUN)
            } else {
                stateComponent.changeState(IDLE)
            }
            if (stateComponent.currentState == RUN) {
                //println("${tagEntity.center}-->${entity.center}")
                move(it, tpf)
            }
        }
    }

    private fun move(tagEntity: Entity, tpf: Double) {
        // 计算entity到tagEntity的向量
        val vector = tagEntity.center.subtract(entity.center).normalize()
        // 将entity旋转到向量的方向
        entity.rotateToVector(vector)
        // entity向tagEntity位置位移
        entity.translateTowards(tagEntity.center, tpf * speed)
        //println("-entity.center>>${entity.center}-tagEntity>>${tagEntity.center}")
    }


}